package com.javajun.endofterm.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Xiong Limin
 * Date: 2020-11-26-10:26 上午
 */
public class CommonService<T, ID extends Serializable> {

    @Autowired
    private CommonRepository<T, ID> commonRepository;

    public List<T> findAll(){
        return commonRepository.findAll();
    }

    public T findById(ID id) {
        Optional<T> optional = commonRepository.findById(id);
        if(optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    public long count() {
        return commonRepository.count();
    }

    @Transactional
    public void save(T entity) {
        commonRepository.save(entity);
    }

    public void delete(T entity) {
        commonRepository.delete(entity);
    }

    @Transactional
    public void deleteById(ID id) {
        commonRepository.deleteById(id);
    }

    public List<T> findAll(Sort sort){
        return commonRepository.findAll(sort);
    }

    public List<T> findAll(Specification<T> spec){
        return commonRepository.findAll(spec);
    }

    public Page<T> findAll(Pageable pageable){
        return commonRepository.findAll(pageable);
    }

    public Page<T> findAll(Specification<T> spec,Pageable pageable){
        return commonRepository.findAll(spec,pageable);
    }

    public List<T> findAll(Specification<T> spec,Sort sort){
        return commonRepository.findAll(spec,sort);
    }
}
